package com.example.todoapp.tag;


import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/api")
public class TagController {

    // 模拟数据存储
    private List<Tag> tags = new ArrayList<>();
    private int nextId = 1;

    public TagController() {
        // 初始化测试数据
        Tag tag = new Tag();
        tag.setId(nextId++);
        tag.setName("test-tag");
        tag.setDescription("test");
        tag.setCreatedAt(LocalDateTime.now());
        tag.setUpdatedAt(LocalDateTime.now());
        tags.add(tag);
    }

    @GetMapping("/tags")
    public Result<List<Tag>> getAllTags() {
        return Result.success(tags);
    }

    @GetMapping("/tag/{id}")
    public Result<Tag> getTagById(@PathVariable Integer id) {
        return tags.stream()
                .filter(tag -> tag.getId().equals(id))
                .findFirst()
                .map(Result::success)
                .orElseGet(() -> Result.success(null));
    }

    @PostMapping("/tag")
    public Result<Tag> createTag(@RequestBody Tag newTag) {
        newTag.setId(nextId++);
        newTag.setCreatedAt(LocalDateTime.now());
        newTag.setUpdatedAt(LocalDateTime.now());
        tags.add(newTag);
        return Result.success(newTag);
    }

    @PostMapping("/tag/{id}")
    public Result<Tag> updateTag(@PathVariable Integer id, @RequestBody Tag updatedTag) {
        return tags.stream()
                .filter(tag -> tag.getId().equals(id))
                .findFirst()
                .map(tag -> {
                    tag.setName(updatedTag.getName());
                    tag.setDescription(updatedTag.getDescription());
                    tag.setUpdatedAt(LocalDateTime.now());
                    return Result.success(tag);
                })
                .orElseGet(() -> Result.success(null));
    }
}
